<?php

class Project_Db_Table_Row extends Zend_Db_Table_Row {
	public function getFieldName($name) {
		if (parent::__isset($name)) {
			return $name;

		} else {
			$transformed = Project_String::transformCaseToUnderline($name);
			if (parent::__isset($transformed)) {
				return $transformed;
			}			
		}

		return $name;
	}

	public function __isset($name) {
		return
			parent::__isset($name) ||
			parent::__isset(Project_String::transformCaseToUnderline($name));
	}

	public function __get($name) {
		return parent::__get($this->getFieldName($name));
	}

	public function __set($name, $value) {
		return parent::__set($this->getFieldName($name), $value);
	}

	public function getPrimaryKeyName() {
		return $this->getTable()->getPrimaryKeyName();
	}

	public function getId() {
		return $this->offsetGet($this->getPrimaryKeyName());
	}

	public function getModifiedFields() {
		return $this->_modifiedFields;
	}
	
	public function getLinks($modelToInclude) {
		$model = Model::get($modelToInclude);
		$list = $model->fetchEntries(
			array(
				$this->getPrimaryKeyName() => $this->getId()
			)
		);
		
		return $list;
	}
	
	public function getLinksIds($modelToInclude, $key) {
		$links = $this->getLinks($modelToInclude);
		$array_ids = array();
		
		if($links) {
			foreach ($links AS $item) {
				array_push(
					$array_ids,
					$item->$key
				);
			}
		}
		
		return $array_ids;
	}
	
	public function setLinks($modelToInclude, $key, $value) {
		if($value) {
			foreach ($value AS $id) {
				Model::get($modelToInclude)->insert(
					array(
						$this->getPrimaryKeyName() => $this->getId(), 
						$key => $id
					)
				);
			}
		}
	}
}
